﻿/*
Copyright © 2010 François Karman

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

See <license.txt> for the complete license of the software.
*/

using System;
using System.Windows.Markup;

namespace Faz.Dependencies
{
    /// <summary>
    /// Extension that replace the <see cref="System.Windows.StaticResourceExtension"/> and
    /// <see cref="System.Windows.DynamicResourceExtension"/> to avoid Merged dictionary
    /// without issuing the memory cost of a dynamic resource.
    /// </summary>
    public class ApplicationResourceExtension : MarkupExtension
    {
        /// <summary>
        /// Initializes a new instance of the ApplicationResourceExtension class.
        /// </summary>
        public ApplicationResourceExtension()
        {
        }

        /// <summary>
        /// Initializes a new instance of the ApplicationResourceExtension class
        /// for a specific resource.
        /// </summary>
        /// <param name="resourceKey">The identifier of the associated resource.</param>
        public ApplicationResourceExtension(object resourceKey)
        {
            this.ResourceKey = resourceKey;
        }

        /// <summary>
        /// Gets or sets the identifier of the associated resource.
        /// </summary>
        [ConstructorArgument("resourceKey")]
        public object ResourceKey { get; set; }

        /// <summary>
        /// Retrieves the resource associated with the
        /// <see cref="ApplicationResourceExtension.ResourceKey"/> property.
        /// </summary>
        /// <param name="serviceProvider">The parameter is not used.</param>
        /// <returns>The associated resource or <c>null</c>.</returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (this.ResourceKey == null)
            {
                return null;
            }
            else
            {
                return App.Current.FindResource(this.ResourceKey);
            }
        }
    }
}
